<template>
  <div class="camera_outer">
    <div style="text-align: center">
      <video :style="{transform:'rotateY('+rotate+'deg)'}" id="videoCamera" :width="videoWidth" :height="videoHeight" playsinline autoplay x5-video-player-type="h5" style="object-fit:fill" autoplay></video>
    </div>
    <canvas style="display:none;" id="canvasCamera" :width="videoWidth" :height="videoHeight" ></canvas>
    <div style="text-align: center;">
      <p class="fontSize16">您需要进行本人认证</p>
      <p class="fontSize12">通过后方可进行安全学习</p>
    </div>
    <div style="margin: 16px;">
      <van-button round block @click="setImage" type="info">拍照</van-button>
    </div>
  </div>
</template>

<script>
import dashbordAPI from '../../../../api/dashbordAPI.js'
import signInAPI from '../../../../api/workAPI/signInAPI.js'
export default {
data () {
  return {
    videoWidth: 320,
    videoHeight: 320,
    imgSrc: '',
    thisCancas: null,
    thisContext: null,
    thisVideo: null,
    watchOrientationId: null,
    rotate: 180
  }
},
mounted() {
  this.watchOrientation()
  this.getCompetence()
},
destroyed() {
  this.stopNavigator()
  plus.orientation.clearWatch(this.watchOrientationId);
},
methods: {
  watchOrientation(){
    this.watchOrientationId = plus.orientation.watchOrientation((rotation) => {
      // var a = rotation.alpha
      // var c = rotation.headingAccuracy
      // console.log(a,c)
      // this.rotate = a /
      // console.log(rotation.beta);
      // console.log(rotation.gamma);
    }, (error) =>{
      console.log(error)
    },{"frequency":1000});
  },
  // 调用权限（打开摄像头功能）
  getCompetence () {
    var _this = this
    this.thisCancas = document.getElementById('canvasCamera')
    this.thisContext = this.thisCancas.getContext('2d')
    this.thisVideo = document.getElementById('videoCamera')
    if (navigator.mediaDevices === undefined) {
      navigator.mediaDevices = {}
    }
    if (navigator.mediaDevices.getUserMedia === undefined) {
      navigator.mediaDevices.getUserMedia = function (constraints) {
        var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia
        if (!getUserMedia) {
          return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
        }
        return new Promise(function (resolve, reject) {
          getUserMedia.call(navigator, constraints, resolve, reject)
        })
      }
    }
    if (window.stream) {
      window.stream.getTracks().forEach(track => {
        track.stop();
      });
    }
    // ,facingMode: { exact: "environment" }
    var constraints = window.constraints = {
      audio: false,
      video: {
        sourceId: 'default',
        facingMode:  {
          exact: 'user',
        },
        width: _this.videoWidth,
        height: _this.videoHeight,
      },
    }
    navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
      if ('srcObject' in _this.thisVideo) {
        _this.thisVideo.srcObject = stream
      } else {
        // 避免在新的浏览器中使用它，因为它正在被弃用。
        _this.thisVideo.src = window.URL.createObjectURL(stream)
      }
      _this.thisVideo.onloadedmetadata = function (e) {
        _this.thisVideo.play()
      }
    }).catch(err => {
      console.log(err)
    })
  },

    // 绘制图片（拍照功能）
    setImage () {
      var _this = this
      _this.thisContext.drawImage(_this.thisVideo,0 , 0,_this.videoWidth, _this.videoHeight)
      var image = this.thisCancas.toDataURL('image/png')
      _this.imgSrc = image
      let file = this.dataURLtoFile(_this.imgSrc, 'photo.jpg')
      dashbordAPI.uploadAvatar(file).then(res => {
        signInAPI.getFace(res.fileUrl).then(resData => {
          if (resData.result) {
            _this.$router.push({
              name: 'SignCamera',
            })
          } else {
            _this.$toast.fail('人脸比对不成功')
          }
        })

      })
    },
    // base64转文件
    dataURLtoFile (dataurl, filename) {
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    },
    // 关闭摄像头
    stopNavigator () {
      this.thisVideo.srcObject.getTracks()[0].stop()
    }
  },
}

</script>

<style lang="scss" scoped>
.camera_outer{
  text-align: center;
  margin: 0 auto;
  position: relative;
  overflow: hidden;
  // background: url("../../../assets/images/headPhoto.png") no-repeat center;
  background-size: 100%;
  video,canvas,.tx_img{
    // -moz-transform:scaleX(-1);
    // -webkit-transform:scaleX(-1);
    // -o-transform:scaleX(-1);
    // transform:scaleX(-1);
  }

  .btn_camera{
    position: absolute;
    bottom: 4px;
    left: 0;
    right: 0;
    height: 50px;
    background-color: rgba(0,0,0,0.3);
    line-height: 50px;
    text-align: center;
    color: #fff;
  }
  .bg_r_img{
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;
  }

  .img_bg_camera{
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;
    img{
      width: 100%;
      height: 100%;
    }

    .img_btn_camera{
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 50px;
      line-height: 50px;
      text-align: center;
      background-color: rgba(0,0,0,0.3);
      color: #fff;
      .loding_img{
        width: 50px;
        height: 50px;
      }
    }
  }
}
</style>
